package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.dto.ShoppingCartDTO;
import com.sky.entity.Dish;
import com.sky.entity.Setmeal;
import com.sky.entity.ShoppingCart;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.service.ShoppingCartService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private SetmealMapper setmealMapper;

    @Override
    public void addOne(ShoppingCartDTO dto) {
        ShoppingCart newSC = new ShoppingCart();
        BeanUtils.copyProperties(dto, newSC);
        newSC.setUserId(BaseContext.getCurrentId());

        //查询是否存在
        ShoppingCart searchSC = shoppingCartMapper.selectByShoppingCart(newSC);
        if (searchSC != null) {
            //修改旧的
            searchSC.setNumber(searchSC.getNumber() + 1);
            shoppingCartMapper.update(searchSC);
            return;
        }

        //添加一条新的
        if (newSC.getDishId() != null) {
            Dish dish = dishMapper.getDish(newSC.getDishId());
            newSC.setName(dish.getName());
            newSC.setAmount(dish.getPrice());
            newSC.setImage(dish.getImage());
        } else {
            Setmeal setmeal = setmealMapper.getOne(newSC.getSetmealId());
            newSC.setName(setmeal.getName());
            newSC.setAmount(setmeal.getPrice());
            newSC.setImage(setmeal.getImage());
        }
        newSC.setNumber(1);
        newSC.setCreateTime(LocalDateTime.now());
        shoppingCartMapper.insert(newSC);
    }

    @Override
    public List<ShoppingCart> getList(Long userId) {
        return shoppingCartMapper.getList(userId);
    }

    @Override
    public void cleanAll(Long userId) {
        shoppingCartMapper.deleteAll(userId);
    }

    @Override
    public void sub(ShoppingCartDTO dto) {
        ShoppingCart sc = new ShoppingCart();
        BeanUtils.copyProperties(dto, sc);
        sc.setUserId(BaseContext.getCurrentId());

        ShoppingCart searchSC = shoppingCartMapper.selectByShoppingCart(sc);

        if (searchSC.getNumber() == 1) {
            shoppingCartMapper.deleteOne(searchSC.getId());
        } else {
            searchSC.setNumber(searchSC.getNumber() - 1);
            shoppingCartMapper.update(searchSC);
        }

    }
}
